<?php

class CompanyController extends Controller {
    const PAGE_SIZE=10;

    /**
     * @var string specifies the default action to be 'list'.
     */
    public $defaultAction='create';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'ajaxOnly + autocompletename',
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
        array('allow',  // allow all users to perform 'list' and 'show' actions
        'actions'=>array('list','show','index'),
        'users'=>array('*'),
        ),
        array('allow', // allow authenticated user to perform 'create' and 'update' actions
        'actions'=>array('create','update','autocompletename'),
        'users'=>array('@'),
        ),
        array('allow', // allow admin user to perform 'admin' and 'delete' actions
        'actions'=>array('admin','delete'),
        'users'=>array('admin'),
        ),
        array('deny',  // deny all users
        'users'=>array('*'),
        ),
        );
    }

    /**
     * Shows a particular model.
     */
    public function actionAutoCompleteName() {
        $criteria = new CDbCriteria;
        $returnVal=array();
        $criteria->condition = "cname like :cname";
        $criteria->order = "cname asc";
        $criteria->limit = 10;
        $criteria->params = array(":cname"=>$_GET['term']);
        $company = company::model()->find($criteria);
        if($company != null) {
            $returnVal[] = array('label'=>$company->cname,'id'=>$company->id,'value'=>$company->cname);
        }
        
        $criteria->params = array(":cname"=>$_GET['term']."%");
        $company = company::model()->findAll($criteria);
        foreach($company as $c) {
            $returnVal[] = array('label'=>$c->cname,'id'=>$c->id,'value'=>$c->cname);
        }
        $returnVal[] = array('label'=>'Add new contact','id'=>-1,'value'=>$_GET['term']);
        echo CJSON::encode($returnVal);
    }
    public function actionIndex() {
        echo "this is a test";
    }
    public function actionShow() {
        $this->render('show',array('model'=>$this->loadcustomer()));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'show' page.
     */
     private static function makeError($model,&$errorAttri,&$errorSummary,$contactsprefix='company') {
        foreach($model as $i=>$m) {
            foreach($m->contacts as $g=>$c) {
                foreach($c->getErrors() as $n=>$e) {
                    $_n=$contactsprefix."_contacts[$i][$g][$n]";
                    $errorAttri[]=$_n;
                    if(!in_array($e[0],$errorSummary))
                        $errorSummary[] = $e[0];
                }
            }
            foreach($m->email as $g=>$c) {
                foreach($c->getErrors() as $n=>$e) {
                    $_n=$contactsprefix."_email[$i][$g][$n]";
                    $errorAttri[]=$_n;
                    if(!in_array($e[0],$errorSummary))
                        $errorSummary[] = $e[0];
                }
            }
            foreach($m->getErrors() as $n=>$e) {
                $_n = "[$i]".$n;
                $errorAttri[] = CHtml::resolveName($_m, $_n);
                if(!in_array($e[0],$errorSummary))
                    $errorSummary[] = $e[0];
            }
        }
    }
    public function AssignData(&$ref,$class,$prefix='company') {
        $contacts = array();
        $email = array();
        $c = $prefix.'_contacts';
        $e = $prefix.'_email';
        $i=0;
        foreach($_POST[$prefix.'_contacts'] as $items) {
                $g=0;
                foreach($items as $item) {
                    $contacts[$i][$g] = new $c;
                    $contacts[$i][$g]->attributes = $item;
                    $g++;
                }
                $i++;
            }
            $i=0;
            foreach($_POST[$prefix.'_email'] as $items) {
                $g=0;
                foreach($items as $g=>$item) {
                    $email[$i][$g] = new $e;
                    $email[$i][$g]->attributes = $item;
                    $g++;
                }
                $i++;
            }

            $i=0;
            foreach($_POST[$class] as $item) {
                    $ref[$i] = new $class;
                    $ref[$i]->attributes = $item;
                    $ref[$i]->contacts = $contacts[$i];
                    $ref[$i]->email = $email[$i];
                    $i++;
            }
    }
    public function actionCreate() {
        $models['company'] = new company;
        $models['company_address'][0] = new company_address;
        $models['company_address'][1] = new company_address;
        $models['company_members'][0] = new company_members;
        $models['company_members'][0]->contacts[0] = new company_members_contacts;
        $models['company_members'][0]->email[0] = new company_members_email;
        $models['company_members'][0]->contacts[0]->type = 1;
        $models['company_address'][0]->contacts[0] = new company_contacts;
        $models['company_address'][0]->contacts[1] = new company_contacts;
        $models['company_address'][0]->email[0] = new company_email;
        $models['company_address'][0]->contacts[0]->type=0;
        $models['company_address'][0]->contacts[1]->type=10;
        $models['company_address'][1]->contacts[0] = new company_contacts;
        $models['company_address'][1]->contacts[1] = new company_contacts;
        $models['company_address'][1]->contacts[0]->type=0;
        $models['company_address'][1]->contacts[1]->type=10;
        $this->setReferrer('company');
        if(isset($_POST['company'])) {
            $models['company']->attributes = $_POST['company'];
            $this->AssignData($models['company_address'],'company_address','company');
            $this->AssignData($models['company_members'],'company_members','company_members');
            $models['company']->address = $models['company_address'];
            $models['company']->members = $models['company_members'];
            //print_r($models['company']->address);
            $transaction = Yii::app()->db->beginTransaction();
            if($models['company']->saveCompany()) {
                $transaction->commit();
                if(Yii::app()->request->isAjaxRequest) {
                    $r = $this->getReferrer('company');
                    $id = $models['company']->id;
                    if(!empty($r)){
                        echo "$.ajax({data:{id:'$id'},'url':'$r',dataType:'script',global:true});";
                    }
                }
                else
                    $this->redirect(array('show','id'=>$models['company']->id));
            }
            else{
                $transaction->rollback();
                if(Yii::app()->request->isAjaxRequest) {
                    $errorAttri=array();
                    $errorSummary = array();
                    foreach($models['company']->getErrors() as $n=>$e) {
                        $errorAttri[] = CHtml::resolveName($models['company'], $n);
                        if(!in_array($e[0],$errorSummary))
                            $errorSummary[] = $e[0];
                    }
                    $this->makeError($models['company_address'],$errorAttri,$errorSummary,'company');
                    $this->makeError($models['company_members'],$errorAttri,$errorSummary,'company_members');
                    $err = $this->makeErrorByName($errorAttri);
                    $err .= $this->makeJsErrorMsg($errorSummary);
                    echo $err;
                }
            }
        }
        $this->makeSubmitScript();
        if(Yii::app()->request->isAjaxRequest) {
            echo $this->renderPartial('form', array('models'=>$models,'update'=>false),true,true);
        }
        else
            $this->render('create',array('models'=>$models,'update'=>false));
    }
    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'show' page.
     */
    public function actionUpdate() {
        $model=$this->loadcustomer();
        if(isset($_POST['customer'])) {
            $model->attributes=$_POST['customer'];
            if($model->save())
                $this->redirect(array('show','id'=>$model->id));
        }
        $this->render('update',array('model'=>$model));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'list' page.
     */
    public function actionDelete() {
        if(Yii::app()->request->isPostRequest) {
        // we only allow deletion via POST request
            $this->loadcustomer()->delete();
            $this->redirect(array('list'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionList() {
        $criteria=new CDbCriteria;

        $pages=new CPagination(contact::model()->count($criteria));
        $pages->pageSize=self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $models=contact::model()->findAll($criteria);

        $this->render('list',array(
            'models'=>$models,
            'pages'=>$pages,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $this->processAdminCommand();

        $criteria=new CDbCriteria;

        $pages=new CPagination(customer::model()->count($criteria));
        $pages->pageSize=self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort=new CSort('customer');
        $sort->applyOrder($criteria);

        $models=customer::model()->findAll($criteria);

        $this->render('admin',array(
            'models'=>$models,
            'pages'=>$pages,
            'sort'=>$sort,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadcustomer($id=null) {
        if($this->_model===null) {
            if($id!==null || isset($_GET['id']))
                $this->_model=company::model()->findbyPk($id!==null ? $id : $_GET['id']);
            
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Executes any command triggered on the admin page.
     */
    protected function processAdminCommand() {
        if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete') {
            $this->loadcustomer($_POST['id'])->delete();
            // reload the current page to avoid duplicated delete actions
            $this->refresh();
        }
    }
}
